<!DOCTYPE html>
<html lang="en">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="manifest" href="/manifest.json">

    <link rel="apple-touch-icon" href="/icon.png" />
    <!-- 添加到主屏后的标题 和 short_name一致 -->
    <meta name="apple-mobile-web-app-title" content="标题">
    <!-- 隐藏safari地址栏 standalone模式下默认隐藏 -->
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <!-- 设置状态栏颜色 -->
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
    <link rel="stylesheet" href="main.css">
<!--    <title>Document</title>-->
</head>
<body>
    <h1>this is something</h1>
    <ul></ul>
    <script src="main.js"></script>
    <script>
        function urlBase64ToUint8Array(base64String) {
            const pdding = '='.repeat((4 - base64String.length % 4) % 4);
            const base64 = (base64String + pdding)
                            .replace(/-/g, '+')
                            .replace(/_/g, '/');
            const rowData = window.atob(base64);
            const outputArray = new Uint8Array(rowData.length);
            for (let i = 0; i < rowData.length; ++i) {
                outputArray[i] = rowData.charCodeAt(i);
            }

            return outputArray;
        }
        // 给网站注册service worker
        // 注册时机： 等待资源加载完成后再开一个线程来加载service worker
        window.addEventListener('load', async () => {
            if (navigator.serviceWorker) {
                // web worker
                let registertion = await navigator.serviceWorker.register('/sw.js');
                console.log(registertion);

                //Push api
                // 也是依赖于Service Worker
                await navigator.serviceWorker.ready;
                const convertedVapidKey = urlBase64ToUint8Array('BKn9WZWSFKaRlWfxwg32xV5M_IYr_nUFRQnS8tb_fR_1X1Ga_xP2TGfObHtKZzDeVBSJfoNasD_-N5qnYyg5enc');
                let pushSubscription = await registertion.pushManager.subscribe({
                    userVisibleOnly: true, // 用户可见性
                    applicationServerKey: convertedVapidKey
                });
                console.log(pushSubscription);
                //  拿到pushSubscription，然后转交给服务器，服务器就可以用他来推送消息给浏览器
                fetch('/add-sub', {
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    method: 'post',
                    body: JSON.stringify(pushSubscription)
                })
            }
        })
    </script>
</body>
</html>